package com.chiffoyqc.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by Administrator on 2017/6/26.
 */
public class WxPayUtils {

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, Object> xmlToMap(String strXML) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
        org.w3c.dom.Document doc = documentBuilder.parse(stream);
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getDocumentElement().getChildNodes();
        for (int idx = 0; idx < nodeList.getLength(); ++idx) {
            Node node = nodeList.item(idx);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                data.put(element.getNodeName(), element.getTextContent());
            }
        }
        try {
            stream.close();
        } catch (Exception ex) {
            // do nothing
        }
        return data;
    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<Object, Object> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (Object key : data.keySet()) {
            Object valueObj = data.get(key);
            String value = null;
            if (valueObj instanceof String) {
                value = (String) valueObj;
            } else if (valueObj instanceof Integer) {
                value = String.valueOf(valueObj);
            }
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement((String) key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }

    /**
     * 多层级map转换
     * */
    public static String callMapToXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        mapToXML2(map, sb);
        sb.append("</xml>");
        try {
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 多层级map转换
     * */
    private static void mapToXML2(Map map, StringBuffer sb) {
        StringBuffer stringBuffer = new StringBuffer();
        Set set = map.keySet();
        for (Iterator it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (null == value)
                value = "";
            if("class".equals(key)){
                continue;
            }
            if (value.getClass().getName().equals("java.util.ArrayList")) {
                ArrayList list = (ArrayList) map.get(key);
                stringBuffer.append("<");
                stringBuffer.append(key);
                stringBuffer.append(">");
                sb.append(stringBuffer);
                stringBuffer.setLength(0);
                for (int i = 0; i < list.size(); i++) {
                    HashMap hm = (HashMap) list.get(i);
                    mapToXML2(hm, sb);
                }
                stringBuffer.append("</");
                stringBuffer.append(key);
                stringBuffer.append(">");
                sb.append(stringBuffer);
                stringBuffer.setLength(0);

            } else  {
                if (value instanceof HashMap) {
                    stringBuffer.append("<");
                    stringBuffer.append(key);
                    stringBuffer.append(">");
                    sb.append(stringBuffer);
                    stringBuffer.setLength(0);
                    mapToXML2((HashMap) value, sb);
                    stringBuffer.append("</");
                    stringBuffer.append(key);
                    stringBuffer.append(">");
                    sb.append(stringBuffer);
                    stringBuffer.setLength(0);
                } else {
                    stringBuffer.append("<");
                    stringBuffer.append(key);
                    stringBuffer.append(">");
                    stringBuffer.append(value);
                    stringBuffer.append("</");
                    stringBuffer.append(key);
                    stringBuffer.append(">");
                    sb.append(stringBuffer);
                    stringBuffer.setLength(0);
                }

            }

        }
    }

    /**
     * javaBean 转 Map
     * @param object 需要转换的javabean
     * @return  转换结果map
     * @throws Exception
     */
    public static Map<Object, Object> beanToMap(Object object) throws Exception
    {
        Map<Object, Object> map = new HashMap<>();

        Class cls = object.getClass();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
        return map;
    }

    /**
     * <summary>
     * 根据当前系统时间加随机序列来生成订单号
     * </summary>
     * <returns>订单号</returns>
     */
    public static String generateOutTradeNo(String mch_id, String dateTime, int randomInt) {
        return String.format("%1$s%2$s%3$d", mch_id, dateTime, randomInt);
    }

    /**
     * 生成wxPay签名
     * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_3
     * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=20_1
     */
    public static String getSignature(Map<Object, Object> beanMap,String userkey) {
        /**
         * #1.对参数按照key=value的格式，并按照参数名ASCII字典序排序生成字符串
         * */
        List<String> list = new ArrayList<String>();
        Object valueObj;
        for (Object key : beanMap.keySet()) {
            valueObj = beanMap.get(key);
            if(valueObj == null || "class".equals(key)){
                continue;
            }
            if ("sign".equals((String) key) || "key".equals((String) key)) {
                continue;
            }
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("&");
            stringBuffer.append((String) key);
            stringBuffer.append("=");

            String value = null;
            if (valueObj instanceof String) {
                value = (String) valueObj;
            } else if (valueObj instanceof Integer) {
                value = String.valueOf(valueObj);
            }

            stringBuffer.append(value);

            list.add(stringBuffer.toString());
        }

        Object[] objects = list.toArray();


        Arrays.sort(objects);

//        System.out.println("objects: " + objects.toString());

        /**
         * #2.连接商户key
         * */
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0, len = objects.length; i < len; i++) {
            stringBuffer.append((String) objects[i]);
        }
        stringBuffer.append("&key=");
        stringBuffer.append(userkey);

        String string1 = stringBuffer.toString().substring(1);

        /**
         * #3.生成sign并转成大写
         * */
        String sign = DigestUtils.md5Hex(string1).toUpperCase();
        return sign;
//
    }

    /**
     * 获得指定长度的noncestr算法
     */
    public static String getNonceStr(int length) {
        String basestr = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(basestr.length());
            stringBuffer.append(basestr.charAt(number));
        }
        return stringBuffer.toString();
    }
}
